package com.srinivasu;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class SortMapByValue {

	
	public static void main(String[] args) {
		trader t1 = new trader();
		t1.setNo_of_purchases(200.40f);
		t1.setNo_of_sales(567.787f);
		
		trader t2 = new trader();
		t2.setNo_of_purchases(100.40f);
		t2.setNo_of_sales(867.787f);
		
		trader t3 = new trader();
		t3.setNo_of_purchases(500.40f);
		t3.setNo_of_sales(57.787f);
		
		HashMap<String, trader> map = new HashMap<String, trader>();
		map.put("first", t1);
		map.put("second", t2);
		map.put("third", t3);
		
		
		System.out.println(map);
		//map.entrySet() returns collection is a Map.Entry 
		
		List list = new LinkedList(map.entrySet());
		Collections.sort(list, new Comparator() {

			@Override
			public int compare(Object o1, Object o2) {
				trader t1 = (trader) ((Map.Entry)(o1)).getValue();
				trader t2 = (trader) ((Map.Entry)(o2)).getValue();
				
				return (int) (t2.getNo_of_purchases() - t1.getNo_of_purchases());
			}
			
		});
		
		Map sortedMap = new LinkedHashMap();
		 Iterator it = list.iterator();
		 while (it.hasNext()) {
			Map.Entry object = (Map.Entry) it.next();
			sortedMap.put(object.getKey(), object.getValue());
			
		}
		 System.out.println(sortedMap);
		
		

	}

}
class trader{
	float no_of_purchases;
	float no_of_sales;
	public float getNo_of_purchases() {
		return no_of_purchases;
	}
	public void setNo_of_purchases(float noOfPurchases) {
		no_of_purchases = noOfPurchases;
	}
	public float getNo_of_sales() {
		return no_of_sales;
	}
	public void setNo_of_sales(float noOfSales) {
		no_of_sales = noOfSales;
	}
	@Override
	public String toString() {
		return "trader [no_of_purchases=" + no_of_purchases + ", no_of_sales="
				+ no_of_sales + "]";
	}
	
}